<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>膳食计划管理</title>
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <header>
        <h1>个人健康管理系统</h1>
        <nav>
            <ul>
                <li><a th:href="@{/}">首页</a></li>
                <li><a th:href="@{/foods}">食物管理</a></li>
                <li><a th:href="@{/users}">用户管理</a></li>
                <li><a th:href="@{/dietplans}" class="active">膳食计划</a></li>
                <li><a th:href="@{/userhealthindices}">健康指标</a></li>
            </ul>
        </nav>
    </header>

    <main class="container">
        <h2>膳食计划管理</h2>

        <!-- 添加膳食计划表单 -->
        <h3>添加新膳食计划</h3>
        <form id="addDietPlanForm" action="/api/dietplans" method="post">
            <div class="form-group">
                <label for="addPlanName">名称:</label>
                <input type="text" id="addPlanName" name="planName" required>
            </div>
            <div class="form-group">
                <label for="addDescription">描述:</label>
                <input type="text" id="addDescription" name="description">
            </div>
            <div class="form-group">
                <label for="addCaloriesTarget">卡路里目标:</label>
                <input type="number" id="addCaloriesTarget" name="caloriesTarget" required>
            </div>
            <div class="form-group">
                <label for="addDurationDays">持续天数:</label>
                <input type="number" id="addDurationDays" name="durationDays" required>
            </div>
            <div class="form-group">
                <label for="addGoal">目标:</label>
                <input type="text" id="addGoal" name="goal">
            </div>
            <div class="form-group">
                <label for="addUserId">用户ID:</label>
                <input type="number" id="addUserId" name="userId" required>
            </div>
            <div class="form-group">
                <label for="addStartDate">开始日期:</label>
                <input type="date" id="addStartDate" name="startDate">
            </div>
            <div class="form-group">
                <label for="addEndDate">结束日期:</label>
                <input type="date" id="addEndDate" name="endDate">
            </div>
            <button type="submit" class="btn">添加膳食计划</button>
        </form>

        <!-- 膳食计划列表 -->
        <h3>所有膳食计划</h3>
        <table id="dietPlanTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>名称</th>
                    <th>描述</th>
                    <th>卡路里目标</th>
                    <th>持续天数</th>
                    <th>目标</th>
                    <th>用户ID</th>
                    <th>创建时间</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- 膳食计划数据将通过JavaScript加载 -->
            </tbody>
        </table>

        <!-- 编辑膳食计划表单 (初始隐藏) -->
        <h3 id="editFormTitle" style="display: none;">编辑膳食计划</h3>
        <form id="editDietPlanForm" style="display: none;" action="" method="put">
            <input type="hidden" id="editId" name="id">
            <div class="form-group">
                <label for="editPlanName">名称:</label>
                <input type="text" id="editPlanName" name="planName" required>
            </div>
            <div class="form-group">
                <label for="editDescription">描述:</label>
                <input type="text" id="editDescription" name="description">
            </div>
            <div class="form-group">
                <label for="editCaloriesTarget">卡路里目标:</label>
                <input type="number" id="editCaloriesTarget" name="caloriesTarget" required>
            </div>
            <div class="form-group">
                <label for="editDurationDays">持续天数:</label>
                <input type="number" id="editDurationDays" name="durationDays" required>
            </div>
            <div class="form-group">
                <label for="editGoal">目标:</label>
                <input type="text" id="editGoal" name="goal">
            </div>
            <div class="form-group">
                <label for="editUserId">用户ID:</label>
                <input type="number" id="editUserId" name="userId" required>
            </div>
            <div class="form-group">
                <label for="editStartDate">开始日期:</label>
                <input type="date" id="editStartDate" name="startDate">
            </div>
            <div class="form-group">
                <label for="editEndDate">结束日期:</label>
                <input type="date" id="editEndDate" name="endDate">
            </div>
            <button type="submit" class="btn">保存更改</button>
            <button type="button" class="btn btn-danger" onclick="hideEditForm()">取消</button>
        </form>

    </main>

    <footer>
        <p>&copy; 2025 个人健康管理系统</p>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            fetchDietPlans();

            // 处理添加膳食计划表单提交
            document.getElementById('addDietPlanForm').addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(event.target);
                const dietPlanData = Object.fromEntries(formData.entries());

                // 将userId转换为User对象 (后端需要User对象，而不是纯ID)
                // 这里简化处理，实际应用中可能需要更复杂的逻辑来获取User对象
                dietPlanData.user = { id: parseInt(dietPlanData.userId) };
                delete dietPlanData.userId; // 移除原始的userId字段

                fetch('/api/dietplans', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(dietPlanData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不佳');
                    }
                    return response.json();
                })
                .then(() => {
                    fetchDietPlans(); // 刷新列表
                    event.target.reset(); // 重置表单
                })
                .catch(error => console.error('添加膳食计划失败:', error));
            });

            // 处理编辑膳食计划表单提交
            document.getElementById('editDietPlanForm').addEventListener('submit', function(event) {
                event.preventDefault();
                const dietPlanId = document.getElementById('editId').value;
                const formData = new FormData(event.target);
                const dietPlanData = Object.fromEntries(formData.entries());

                // 将userId转换为User对象 (后端需要User对象，而不是纯ID)
                dietPlanData.user = { id: parseInt(dietPlanData.userId) };
                delete dietPlanData.userId; // 移除原始的userId字段

                fetch(`/api/dietplans/${dietPlanId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(dietPlanData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不佳');
                    }
                    return response.json();
                })
                .then(() => {
                    fetchDietPlans(); // 刷新列表
                    hideEditForm(); // 隐藏编辑表单
                })
                .catch(error => console.error('更新膳食计划失败:', error));
            });
        });

        function fetchDietPlans() {
            fetch('/api/dietplans')
                .then(response => response.json())
                .then(dietPlans => {
                    const tbody = document.querySelector('#dietPlanTable tbody');
                    tbody.innerHTML = ''; // 清空现有内容
                    dietPlans.forEach(plan => {
                        const row = tbody.insertRow();
                        row.innerHTML = `
                            <td>${plan.id}</td>
                            <td>${plan.planName}</td>
                            <td>${plan.description || ''}</td>
                            <td>${plan.caloriesTarget}</td>
                            <td>${plan.durationDays}</td>
                            <td>${plan.goal || ''}</td>
                            <td>${plan.user ? plan.user.id : 'N/A'}</td>
                            <td>${plan.createdAt ? new Date(plan.createdAt).toLocaleString() : 'N/A'}</td>
                            <td>${plan.updatedAt ? new Date(plan.updatedAt).toLocaleString() : 'N/A'}</td>
                            <td>
                                <button class="btn" onclick="editDietPlan(${plan.id})">编辑</button>
                                <button class="btn btn-danger" onclick="deleteDietPlan(${plan.id})">删除</button>
                            </td>
                        `;
                    });
                })
                .catch(error => console.error('获取膳食计划列表失败:', error));
        }

        function editDietPlan(id) {
            fetch(`/api/dietplans/${id}`)
                .then(response => response.json())
                .then(plan => {
                    document.getElementById('editId').value = plan.id;
                    document.getElementById('editPlanName').value = plan.planName;
                    document.getElementById('editDescription').value = plan.description || '';
                    document.getElementById('editCaloriesTarget').value = plan.caloriesTarget;
                    document.getElementById('editDurationDays').value = plan.durationDays;
                    document.getElementById('editGoal').value = plan.goal || '';
                    document.getElementById('editUserId').value = plan.user ? plan.user.id : '';
                    document.getElementById('editStartDate').value = plan.startDate ? new Date(plan.startDate).toISOString().split('T')[0] : '';
                    document.getElementById('editEndDate').value = plan.endDate ? new Date(plan.endDate).toISOString().split('T')[0] : '';
                    
                    document.getElementById('editFormTitle').style.display = 'block';
                    document.getElementById('editDietPlanForm').style.display = 'block';
                })
                .catch(error => console.error('获取膳食计划详情失败:', error));
        }

        function hideEditForm() {
            document.getElementById('editFormTitle').style.display = 'none';
            document.getElementById('editDietPlanForm').style.display = 'none';
            document.getElementById('editDietPlanForm').reset();
        }

        function deleteDietPlan(id) {
            if (confirm('确定要删除此膳食计划吗？')) {
                fetch(`/api/dietplans/${id}`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不佳');
                    }
                    fetchDietPlans(); // 刷新列表
                })
                .catch(error => console.error('删除膳食计划失败:', error));
            }
        }
    </script>
</body>
</html> 